<template>
  <el-dialog class="public-dialog" title="亚马逊多渠道发货" width="1200" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <el-card shadow="always" class="w-[100%] mb-[6px]">
      <XForm ref="formRef1" :fieldList="fieldList1" :options="formOptions" :rules="rules" :formData="formData" :originOption="originOption">
        <template #ShipWarehouse>
          <el-select-v2
            v-model="formData.ship_warehouse_id"
            :options="originOption.shipWarehouseOpt"
            :placeholder="'请选择发货仓库'"
            style="width: 250px"
            clearable
            filterable
            @change="shipWarehouseChange"
          />
        </template>
        <template #ShippingMethod>
          <el-select-v2
            v-model="formData.shipping_method_id"
            :options="originOption.shippingMethodOpt"
            placeholder="请选择运输方式"
            style="width: 250px"
            clearable
            filterable
            @change="shippingMethodChange"
            :loading="shippingMethodLoading"
          />
        </template>
      </XForm>
    </el-card>
    <!-- 单个操作 -->
    <div v-if="!isBatch">
      <el-card shadow="always" class="w-[450px] h-[500px] inline-block">
        <XForm :fieldList="fieldList2" :options="formOptions" :formData="formData.recipient"> </XForm>
      </el-card>

      <el-card shadow="always" class="w-[450px] h-[500px] ml-[6px] inline-block">
        <XForm ref="formRef3" :fieldList="fieldList3" :options="formOptions" :rules="rules" :formData="formData" :originOption="originOption"> </XForm>
      </el-card>

      <FormTitle title="商品信息" class="mt-[6px]" />
      <el-table :data="formData.items" border class="w-[100%]">
        <el-table-column prop="date" label="图片" width="94">
          <template #default="{ row }">
            <el-image :src="row.main_img" class="w-[68px] h-[68px]" style="border: 0.5px solid #f0f0f0; border-radius: 4px">
              <template #error>
                <img src="~@/assets/images/null-img.png" alt="" />
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="系统SKU / 自定义SKU" width="180">
          <template #header>
            <div>系统SKU</div>
            <div>自定义SKU</div>
          </template>
          <template #default="{ row }">
            <div>{{ row.sku }}</div>
            <div>{{ row.custom_sku }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="platform_sku" label="渠道SKU" width="180">
          <template #header>
            <span><span class="text-red text-[16px]">*</span>渠道SKU</span>
            <el-tooltip class="box-item" effect="dark" content="选择的发货店铺对应的渠道SKU" placement="top">
              <div class="dk-iconfont icon-HintFilled"></div>

              <!-- Download -->
            </el-tooltip>
          </template>
          <template #default="{ row, $index }">
            <div v-if="row.platform_sku">{{ row.platform_sku }}</div>
            <el-button type="primary" @click="addSku(row, $index)" v-else> 添 加 </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="asin" label="ASIN" />
        <el-table-column prop="sku_cn_title" label="商品名称">
          <template #default="{ row }">
            <VText :value="row.sku_cn_title" :line="3" />
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" />
        <el-table-column prop="available_stock" label="可用库存" width="100">
          <template #header>
            <span>可用库存</span>
            <el-tooltip class="box-item" effect="dark" content="选择的发货店铺对应渠道SKU的可用库存" placement="top">
              <div class="dk-iconfont icon-HintFilled"></div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="操作" width="90">
          <template #default="{ row }">
            <el-button text type="primary" @click="resetSku(row)"> 重置 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 批量操作 -->
    <div v-if="isBatch">
      <el-card shadow="always" class="w-[100%] mb-[6px]">
        <XForm ref="formRef3" :fieldList="batchFieldList" :options="formOptions" :rules="rules" :formData="formData" :originOption="originOption"> </XForm>
      </el-card>

      <el-table :data="formData.items" border class="w-[100%]" max-height="440px" :span-method="objectSpanMethod">
        <el-table-column prop="orderIndex" label="序号" width="55" />
        <el-table-column prop="name" label="平台/站点/店铺" width="160">
          <template #header>
            <div>平台/站点</div>
            <div>店铺</div>
          </template>
          <template #default="{ row }">
            <div>{{ row.platform }} / {{ row.site }}</div>
            <div>{{ row.shop }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="系统订单号/平台订单号" width="180">
          <template #header>
            <div>系统订单号</div>
            <div>平台订单号</div>
          </template>
          <template #default="{ row }">
            <div>{{ row.order_sn }}</div>
            <div>{{ row.platform_order_sn }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="date" label="图片" width="94">
          <template #default="{ row }">
            <el-image :src="row.main_img" class="w-[68px] h-[68px]" style="border: 0.5px solid #f0f0f0; border-radius: 4px">
              <template #error>
                <img src="~@/assets/images/null-img.png" alt="" />
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="系统SKU / 自定义SKU" width="180">
          <template #header>
            <div>系统SKU</div>
            <div>自定义SKU</div>
          </template>
          <template #default="{ row }">
            <div>{{ row.sku }}</div>
            <div>{{ row.custom_sku }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="platform_sku" label="渠道SKU" width="180">
          <template #header>
            <span><span class="text-red text-[16px]">*</span>渠道SKU</span>
            <el-tooltip class="box-item" effect="dark" content="选择的发货店铺对应的渠道SKU" placement="top">
              <div class="dk-iconfont icon-HintFilled"></div>
            </el-tooltip>
            <div>ASIN</div>
          </template>
          <template #default="{ row, $index }">
            <el-select v-model="row.platform_sku" placeholder="请选择" allow-create filterable class="w-[100%]" @change="platformSkuChange($event, row)">
              <el-option v-for="item in skuOptions[row.sku] || []" :key="item.label" :label="item.value" :value="item.value"> </el-option>
            </el-select>
            <div>{{ row.asin }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="sku_cn_title" label="商品名称" width="100">
          <template #default="{ row }">
            <VText :value="row.sku_cn_title" :line="3" />
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" />
        <el-table-column prop="available_stock" label="可用库存" width="100">
          <template #header>
            <span>可用库存</span>
            <el-tooltip class="box-item" effect="dark" content="选择的发货店铺对应渠道SKU的可用库存" placement="top">
              <div class="dk-iconfont icon-HintFilled"></div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="操作" width="90">
          <template #default="{ row }">
            <el-button text type="primary" link @click="resetSku(row)"> 重置 </el-button>
            <el-button text type="danger" link @click="resetSku(row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="loading"> 保存 </el-button>
    </template>
  </el-dialog>
  <SelectProduct v-model:visible="visible" :multiple="multiple" :selectIds="productIds" @uploadSku="handleSku" :queryForm="SelectProductForm" ref="SelectProductRef" />
</template>

<script setup lang="jsx">
import { apiGetWarehouseList, feeTrialCalcFreight } from "@/api/public"

import { ElMessage } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import FormTitle from "@/components/XForm/FormTitle.vue"

import SelectProduct from "./SelectProduct.vue"
import { getEnum } from "@/utils/enumUtils"
onMounted(async () => {})

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex < 3) {
    if (row.rowIndex == 0) {
      return { rowspan: row.orderLength, colspan: 1 }
    } else {
      return { rowspan: 0, colspan: 0 }
    }
  }
}

// 发货仓库 更改
const shipWarehouseChange = (e) => {
  formData.value.shipping_method_id = null
  if (e) {
    getShippingMethod(e)
  } else {
    originOption.value.shippingMethodOpt = []
  }
}
// 运输方式 更改
const shippingMethodChange = (e) => {
  formData.value.shipping_method_name = originOption.value.shippingMethodOpt.find((v) => v.value == e)?.label
}
// 获取运输方式
const shippingMethodLoading = ref(false)
const getShippingMethod = (e) => {
  shippingMethodLoading.value = true
  let params = {
    source_os: "oms",
    warehouse: [e],
    customer_order_no: formData.value?.order_sn || formData.value?.items?.[0].order_sn,
    destination_country: formData.value?.recipient?.recipient_country || formData.value?.items?.[0].recipient_country,
  }
  feeTrialCalcFreight(params)
    .then((res) => {
      originOption.value.shippingMethodOpt = res.data.map((v) => ({ label: v.channel_name, value: v.channel_id }))
    })
    .finally(() => (shippingMethodLoading.value = false))
}
// 重置sku信息
const resetSku = (row) => {
  console.log(row)

  row.platform_sku = ""
  row.asin = ""
  row.available_stock = ""
}
const visible = ref(false)
const multiple = ref(false)
const productIds = ref([])
const editGoodsRowIndex = ref(null)
const SelectProductForm = ref({})
const SelectProductRef = ref()
const addSku = (row, index) => {
  console.log(row)
  if (!formData.value.ship_warehouse_id) {
    ElMessage({ message: "请先选择发货仓库！", type: "warning" })
    return
  }
  SelectProductForm.value = {
    warehouse_id: [formData.value.ship_warehouse_id],
  }
  console.log(SelectProductForm.value)
  visible.value = true
  SelectProductRef.value.form.goods_sku = row.sku
  editGoodsRowIndex.value = index
}

const handleSku = (v) => {
  formData.value.items[editGoodsRowIndex.value] = {
    ...formData.value.items[editGoodsRowIndex.value],
    platform_sku: v.seller_sku,
    asin: v.asin,
    available_stock: v["afn-fulfillable-quantity"],
    // available_stock: v["afn-fulfillable-quantity"]
  }
}

import api from "./api"
const props = defineProps({})
const modelValue = ref(false)
const formData = ref({})

const formOptions = { inline: true, labelWidth: "100px" }

const originOption = ref({
  shipWarehouseOpt: [],
  shippingMethodOpt: [],
})
const publicStyle = { style: { width: "280px" } }
const fieldList1 = [
  { type: "title", label: "发货仓库与运输方式" },
  { field: "ship_warehouse_id", slot: "ShipWarehouse", label: "发货仓库" },
  { field: "shipping_method_id", slot: "ShippingMethod", label: "运输方式" },
]
const fieldList2 = [
  { type: "title", label: "收件信息" },
  { field: "buyer_name", label: "收件人姓名", disabled: true, ...publicStyle },
  { field: "recipient_phone", label: "联系电话", disabled: true, ...publicStyle },
  { field: "recipient_email", label: "邮箱", disabled: true, ...publicStyle },
  { field: "recipient_country", label: "国家", disabled: true, ...publicStyle },
  { field: "recipient_province", label: "州/省份", disabled: true, ...publicStyle },
  { field: "city", label: "市/区", disabled: true, ...publicStyle },
  { field: "recipient_email", label: "邮箱", disabled: true, ...publicStyle },
  { field: "recipient_preferred_address", label: "详细地址", disabled: true, ...publicStyle },
  { field: "recipient_secondary_address", label: "详细地址2", placeholder: " ", disabled: true, ...publicStyle },
]
const fieldList3 = [
  { type: "title", label: "订单信息" },
  { field: "order_sn", label: "系统订单号", disabled: true, ...publicStyle },
  { field: "platform_order_sn", label: "平台订单号", disabled: true, ...publicStyle },
  { type: "title", label: "发货信息" },
  { field: "order_sn", label: "订单编号", ...publicStyle, disabled: true, default: "<div style='line-height:20px'>说明：默认设置为系统订单号，后续费用结算后，根据系统订单号关联到原订单</div>" },
  { field: "platform_shipping_method_id", label: "配送服务", type: "select", originField: "amazon_shipping_speed_category", options: { placeholder: "配送服务" }, ...publicStyle },
  { field: "order_time", label: "订单日期", type: "dateTimeRangeNorm", itemProps: { type: "datetime" }, ...publicStyle },
  { field: "order_comment", label: "面单备注", ...publicStyle },
]
const batchFieldList = [
  { type: "title", label: "平台信息" },
  { field: "platform_shipping_method_id", label: "配送服务", type: "select", originField: "amazon_shipping_speed_category", options: { placeholder: "配送服务" }, ...publicStyle },
  { field: "order_comment", label: "面单备注", ...publicStyle },
]
const rules = {
  ship_warehouse_id: [{ required: true, message: "请选择", trigger: "change" }],
  shipping_method_id: [{ required: true, message: "请选择", trigger: "change" }],
  platform_shipping_method_id: [{ required: true, message: "请选择", trigger: "change" }],
  order_time: [{ required: true, message: "请选择", trigger: "change" }],
}

const emit = defineEmits(["refresh", "submit"])

const loading = ref(false)

const formRef1 = ref()
const formRef3 = ref()
const handleSave = async () => {
  loading.value = true
  try {
    let tableIdx = formData.value.items.findIndex((v) => !v.platform_sku)
    if (tableIdx != -1) {
      return ElMessage({ message: `第${tableIdx + 1}条数据渠道SKU未选择！`, type: "warning" })
    }

    await formRef1.value.submit()
    await formRef3.value.submit()
    let keys = ["order_id", "ship_warehouse_id", "shipping_method_id", "shipping_method_name", "order_time", "order_comment", "platform_shipping_method_id"]
    let itemsKey = ["sku", "custom_sku", "platform_sku", "asin", "quantity", "id", "order_item_id", "order_id"]
    let params = {}
    keys.forEach((key) => {
      params[key] = formData.value[key]
    })
    params.items = formData.value.items.map((v) => {
      let row = {}
      itemsKey.forEach((key) => {
        row[key] = v[key]
      })
      return row
    })
    if (isBatch.value) {
      let paramsObj = {}
      params.items.forEach((item) => {
        if (!paramsObj[item.order_id]) paramsObj[item.order_id] = { ...params, order_id: item.order_id, items: [] }
        paramsObj[item.order_id]?.items.push(item)
      })
      paramsObj = Object.values(paramsObj)
      api.saveBatch(paramsObj).then((res) => {
        ElMessage.success("保存成功！")
        handleClose(1)
      })
    } else {
      api.save(params).then((res) => {
        ElMessage.success("保存成功！")
        handleClose(1)
      })
    }
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
import { getChannelSku } from "@/api/public.js"
const config = ref({
  title: "",
  header: "",
  columns: [],
})

// const optionsList = computed(() => {
//   const local = useSelectOptionsStore.selectShippingMethod
//   if (!local.length) {
//     useSelectOptionsStore.getOptions(() => {
//       tmsOverallOptions({
//         params: ["mapChannel"],
//       }).then((res) => {
//         useSelectOptionsStore.setStore(res.data.mapChannel, "selectShippingMethod")
//       })
//     })
//   }
//   return local
// })
const getBatchOpt = () => {
  apiGetWarehouseList({ wms_platform: ["1"], shop_id: [] }).then((res) => {
    originOption.value.shipWarehouseOpt = res.data.map((v) => ({ label: v.warehouse_name, value: v.id }))
  })
}
// 渠道sku变动
const platformSkuChange = (e, row) => {
  // row.asin = skuOptions.value[row.sku].find((v) => v.value == e)?.asin
  let item = skuOptions.value[row.id].find((v) => v.value == e)
  row.asin = item?.asin
  row.available_stock = item.available_stock
}
const isBatch = ref(false)

const skuOptions = ref({})

const tableData = ref([])
const open = async (row, batch = false) => {
  isBatch.value = batch
  let optData = await getEnum(["amazon_shipping_speed_category"])
  originOption.value.amazon_shipping_speed_category = optData.amazon_shipping_speed_category
  modelValue.value = true

  if (batch) {
    // formData.value.order_id = row.map((v) => v.id)
    // 批量
    formData.value.platform_shipping_method_id = 3
    let items = row.map((v, idx) => {
      console.log(v)
      v.items = v.items.map((x, i) => ({
        ...x,
        platform: v.platform,
        site: v.site,
        shop: v.shop,
        order_sn: v.order_sn,
        platform_order_sn: v.platform_order_sn,

        // 自定义参数
        order_id: v.id,
        shop_id: v.shop_id,
        recipient_country: v.recipient.recipient_country,
        orderLength: v.items.length,
        rowIndex: i,
        orderIndex: idx + 1,
      }))

      return v.items
    })
    items = items.flat()
    items = items.map((v) => ({ ...v, platform_sku: "" }))

    formData.value.items = items
    // 获取渠道sku
    formData.value.items.forEach(async (item) => {
      const { data } = await getChannelSku({ goods_sku_list: [item.sku], shop_id: item.shop_id, platform: item.platform })
      // 初始化渠道SKU枚举
      if (data.length) {
        skuOptions.value[item.sku] = data.map((v) => ({ label: v.platform_sku, value: v.platform_sku, asin: v.asin }))
      } else {
        skuOptions.value[item.sku] = [{ label: item.sku, value: item.sku, asin: item.asin }]
      }
      item.platform_sku = skuOptions.value[item.sku]?.[0]?.value || item.sku
    })
    getBatchOpt()
  } else {
    // 单个
    formData.value = JSON.parse(JSON.stringify(row))

    // amazon 订单
    // shipping_method_id
    if (formData.value.platform_id == 2) {
      formData.value.platform_shipping_method_id = originOption.value.amazon_shipping_speed_category.find((v) => v.label.includes(formData.value.platform_shipping_method))?.value || ""

      // apiGetWarehouseList({ wms_platform: ["1"], shop_id: [row.shop_id] }).then((res) => {
      //   originOption.value.shipWarehouseOpt = res.data.map((v) => ({ label: v.warehouse_name, value: v.id }))
      // })
    } else {
      formData.value.platform_shipping_method_id = 3
      // apiGetWarehouseList({ wms_platform: ["1"], shop_id: [] }).then((res) => {
      //   originOption.value.shipWarehouseOpt = res.data.map((v) => ({ label: v.warehouse_name, value: v.id }))
      // })
    }

    let warehouseParams = { wms_platform: ["1"] }
    if (formData.value?.shop_id) warehouseParams.shop_id = [formData.value?.shop_id]
    apiGetWarehouseList(warehouseParams).then((res) => {
      originOption.value.shipWarehouseOpt = res.data.map((v) => ({ label: v.warehouse_name, value: v.id }))
    })

    formData.value.items.forEach((item) => {
      item.platform_sku = ""
    })
    formData.value.recipient.buyer_name = `${formData.value?.recipient?.recipient_name} ${formData.value?.recipient?.recipient_last_name}`
    // getShippingMethod(formData.value.ship_warehouse_id)
    formData.value.ship_warehouse_id = null
    formData.value.shipping_method_id = null
    formData.value.order_id = formData.value.id
    formData.value.recipient.city = `${formData.value.recipient.recipient_city} ${formData.value.recipient.recipient_region}`
  }

  formData.value.order_comment = "Thank you for your order !"
  // console.log(formData.value)
}
const handleClose = (refresh) => {
  modelValue.value = false
  originOption.value.shippingMethodOpt = []
  if (refresh == 1) emit("refresh")
}

defineExpose({
  open,
})
</script>
<style lang="scss" scoped></style>
